package com.schoolhelper.social.controller;

import com.schoolhelper.social.domain.Message;
import com.schoolhelper.social.service.MessageService;
import com.schoolhelper.social.service.FriendshipService;
import com.schoolhelper.utils.Result;
import com.schoolhelper.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

@RestController
@RequestMapping("/api/messages")
@CrossOrigin(origins = "http://localhost:8080")
public class MessageController {
    
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
    
    @Autowired
    private MessageService messageService;
    
    @Autowired
    private FriendshipService friendshipService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 发送消息
     */
    @PostMapping("/send")
    public Result<String> sendMessage(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long currentUserId = getCurrentUserId(httpRequest);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            String content = request.get("content").toString();
            Integer messageType = request.get("messageType") != null ? 
                Integer.valueOf(request.get("messageType").toString()) : 0;
            
            // 检查是否为好友关系
            boolean areFriends = friendshipService.areFriends(currentUserId, receiverId);
            
            if (!areFriends) {
                // 检查是否已经发送过消息
                int messageCount = messageService.getMessageCountBetweenUsers(currentUserId, receiverId);
                if (messageCount >= 1) {
                    return Result.error("您与该用户不是好友，只能发送一条消息。请先添加好友后再继续聊天。");
                }
            }
            
            Message message = new Message();
            message.setSenderId(currentUserId);
            message.setReceiverId(receiverId);
            message.setContent(content);
            message.setMessageType(messageType);
            message.setStatus(0); // 未读状态
            message.setCreateTime(new Date()); // 设置创建时间
            
            boolean success = messageService.sendMessage(message);
            if (success) {
                return Result.success("消息发送成功");
            } else {
                return Result.error("消息发送失败");
            }
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return Result.error("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取聊天记录
     */
    @GetMapping("/chat/{userId}")
    public Result<List<Message>> getChatHistory(@PathVariable Long userId, 
                                               @RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "20") int size,
                                               HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            List<Message> messages = messageService.getChatHistory(currentUserId, userId, page, size);
            
            // 标记消息为已读
            messageService.markMessagesAsRead(userId, currentUserId);
            
            return Result.success(messages);
        } catch (Exception e) {
            logger.error("获取聊天记录失败", e);
            return Result.error("获取聊天记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取聊天列表
     */
    @GetMapping("/chats")
    public Result<List<Map<String, Object>>> getChatList(HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            List<Map<String, Object>> chatList = messageService.getChatList(currentUserId);
            return Result.success(chatList);
        } catch (Exception e) {
            logger.error("获取聊天列表失败", e);
            return Result.error("获取聊天列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadCount(HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            int count = messageService.getUnreadCount(currentUserId);
            return Result.success(count);
        } catch (Exception e) {
            logger.error("获取未读消息数量失败", e);
            return Result.error("获取未读消息数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读消息详情（按发送者分组）
     */
    @GetMapping("/unread/details")
    public Result<List<Map<String, Object>>> getUnreadMessageDetails(HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            List<Map<String, Object>> unreadDetails = messageService.getUnreadMessageDetails(currentUserId);
            return Result.success(unreadDetails);
        } catch (Exception e) {
            logger.error("获取未读消息详情失败", e);
            return Result.error("获取未读消息详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查是否可以发送消息
     */
    @GetMapping("/check/{userId}")
    public Result<Map<String, Object>> checkCanSendMessage(@PathVariable Long userId, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }
            
            Map<String, Object> result = new HashMap<>();
            
            // 检查是否为好友关系
            boolean areFriends = friendshipService.areFriends(currentUserId, userId);
            result.put("areFriends", areFriends);
            
            if (!areFriends) {
                // 检查已发送消息数量
                int messageCount = messageService.getMessageCountBetweenUsers(currentUserId, userId);
                result.put("messageCount", messageCount);
                result.put("canSend", messageCount < 1);
                result.put("message", messageCount >= 1 ? 
                    "您与该用户不是好友，只能发送一条消息。请先添加好友后再继续聊天。" : 
                    "您与该用户不是好友，只能发送一条消息，请先添加好友。");
            } else {
                result.put("canSend", true);
                result.put("message", "");
            }
            
            return Result.success(result);
        } catch (Exception e) {
            logger.error("检查发送权限失败", e);
            return Result.error("检查发送权限失败: " + e.getMessage());
        }
    }
    
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                return jwtUtils.getUserIdFromToken(token);
            }
            return null;
        } catch (Exception e) {
            logger.error("获取当前用户ID失败", e);
            return null;
        }
    }
}